import {Restivus} from 'meteor/nimble:restivus';
import {Meteor} from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { Random } from 'meteor/random';
import {PhoneCodes} from '../imports/api/phoneCodes';
import {Families} from '../imports/api/families';
import {Gateways} from '../imports/api/gateways';
if (Meteor.isServer) {
    Meteor.startup(() => {
        let Api = new Restivus({
            useDefaultAuth: true,
            prettyJson: true,
        });
        // 通过接口注册用户
        Api.addRoute('registUser', {authRequired: false}, {
            post: {
                action() { 
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const username = param.username;
                        let nickname = param.nickname;
                        const password = param.password;
                        const code = param.code;
                        console.log('param : ', param);
                        var u = Meteor.users.findOne({username: username});
                        if(u){
                            return {success: false, result: '该手机号已注册！', resultCode: 1002};
                        }else{
                            var up = Meteor.call('findByPhone', username, code);
                            if(up){
                                if(param.nickname && param.nickname != ''){
                                }else{
                                    nickname = username;
                                }
                                var userId = Accounts.createUser({username: username, nickname: nickname, password: password, userType: 'appUser'});
                                if(userId){
                                    Meteor.users.update({_id: userId}, {$set: {nickname: nickname, userType: 'appUser'}});
                                    return {success: true, result: '注册成功！', resultCode: 1000};
                                }else{
                                    return {success: false, result: '注册出错！', resultCode: 1004};
                                }
                            }else{
                                return {success: false, result: '注册码已过期！', resultCode: 1002};
                            }
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        // 通过接口获取验证吗
        Api.addRoute('getVerifyCode', {authRequired: false}, {
            get: {
                action() {
                    console.log('this : ', this);
                    if (this.queryParams) {
                        const telephone = this.queryParams.telephone;
                        const type = this.queryParams.type;
                        const u = Meteor.users.findOne({username: telephone});
                        const code = Math.floor(Math.random() * (9999 - 1000)) + 1000;
                        if(type == 'resetPwd'){
                            var pc1 = PhoneCodes.insert({telephone: telephone, verification_code: code, type: '修改密码'});
                            if (pc1) {
                                try{
                                    var result = HTTP.call("POST", "https://api.mysubmail.com/message/xsend.json",
                                        {params: {"appid": 14256, "to": telephone, "vars": {code: code, time: '5分钟'}, "signature": "b9868a346a2bce9ef4e56729ebb87394", project: "uLASX"}
                                        });

                                    console.log(result);
                                    return {success: true, result: code, resultCode: 1000};

                                } catch (e) {
                                    // Got a network error, time-out or HTTP error in the 400 or 500 range.
                                    // throw new Meteor.Error("error", e);

                                    for(var key in e)
                                    {
                                        console.log(" - " + key + ":"+e[key]);
                                    }

                                    return {success: false, result: '验证码获取失败！', resultCode: 1002};
                                }
                            } else {
                                return {success: false, result: '验证码获取失败！', resultCode: 1002};
                            }
                        }else if(type == 'regist'){
                            if(u){
                                return {success: false, result: '该手机号已注册,可以直接登录！', resultCode: 1002};
                            }else {
                                var pc2 = PhoneCodes.insert({telephone: telephone, verification_code: code, type: '注册用户'});
                                if (pc2) {
                                    try{
                                        var result = HTTP.call("POST", "https://api.mysubmail.com/message/xsend.json",
                                            {params: {"appid": 14256, "to": telephone, "vars": {code: code, time: '5分钟'}, "signature": "b9868a346a2bce9ef4e56729ebb87394", project: "uLASX"}
                                            });

                                        console.log(result);
                                        return {success: true, result: code, resultCode: 1000};

                                    } catch (e) {
                                        // Got a network error, time-out or HTTP error in the 400 or 500 range.
                                        // throw new Meteor.Error("error", e);

                                        for(var key in e)
                                        { 
                                            console.log(" - " + key + ":"+e[key]);
                                        }

                                        return {success: false, result: '验证码获取失败！', resultCode: 1002};
                                    }
                                } else {
                                    return {success: false, result: '验证码获取失败！', resultCode: 1002};
                                }
                            }
                        }else{
                            return {success: false, result: '请确定请求类型！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写手机信息！', resultCode: 1002};
                }
            }
        });
        // 通过接口登录
        Api.addRoute('userLogin', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var username = param.username;
                        var password = param.password;
                        var user = Meteor.users.findOne({username: username});
                        if(user){
                            var result = Accounts._checkPassword(user, password);
                            if(!result.error){
                                // const tokens = user.services && user.services.resume && user.services.resume.loginTokens ? user.services.resume.loginTokens : [];
                                /*console.log('tokens : ', tokens);
                                let token = '';
                                if(tokens && tokens.length > 0){
                                    token = tokens[0].token;
                                }else{*/
                                    var stampedToken = Accounts._generateStampedLoginToken();
                                    var hashStampedToken = Accounts._hashStampedToken(stampedToken);
                                    Accounts._insertHashedLoginToken( result.userId, { token: hashStampedToken.hashedToken} );
                                    token = hashStampedToken.hashedToken;
                                // }

                                const families = Families.find({'createdUser._id': user._id}, {fields: {belongTo: 0, createdUser: 0 }}).count();
                                let bl = false;
                                if(families > 0){
                                    bl = true;
                                }
                                return {success: true, result: {token: token, families: bl, error: ''}, resultCode: 1000};
                            }else{
                                return {success: false, result: {error: '密码不正确，登录失败！'}, resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: {error: '手机号未注册！'}, resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写登录信息！', resultCode: 1002};
                }
            }
        });
        //找回密码
        Api.addRoute('forgotPassword', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        const telephone = param.telephone;
                        const code = param.code;
                        const password = param.password;
                        var u = Meteor.users.findOne({username: telephone});
                        if(u){
                            var pc = Meteor.call('findByPhone',  telephone, code);
                            if(pc){
                                Accounts.setPassword(u._id, password);
                                return {success: true, result: '密码修改成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '验证码已过期！', resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: '找不到该手机号的用户信息，请确认！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写手机信息！', resultCode: 1002};
                }
            }
        });
       /* //修改用户信息接口
        Api.addRoute('updateUser', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var userId = param.userId;
                        var logintoken = param.token;
                        var password = param.password;
                        var user = Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            if(password){
                                delete param.password;
                            }
                            if(param.token){
                                delete param.token;
                            }
                            var u = Meteor.users.update({_id: userId},{$set: param},{filter: false,validate: false});
                            if (u) {
                                if(password && password != ''){
                                    Accounts.setPassword(user._id, password);
                                }
                                return {success: true, result: '用户信息修改成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '用户信息修改失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '非登录用户不能进行修改！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到用户修改信息！', resultCode: 1002};
                }
            }
        });*/
        //修改用户信息接口
        Api.addRoute('updateNickName', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var logintoken = param.token;
                        var nickname = param.nickname;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            var u = Meteor.users.update({_id: user._id},{$set: {nickname: nickname}},{filter: false,validate: false});
                            if (u) {
                                return {success: true, result: '用户昵称修改成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '用户昵称修改失败！', resultCode: 1004};
                            }
                        }else{
                            return {success: false, result: '非登录用户不能进行修改！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到用户修改信息！', resultCode: 1002};
                }
            }
        });
        //获取登录用户信息
        Api.addRoute('getLoginUser', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var logintoken = param.token;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken},{fields: {username: 1, nickname: 1}});
                        if(user) {
                            const families = Families.find({'createdUser._id': user._id}, {fields: {belongTo: 0, createdUser: 0 }}).fetch();
                            let family = {};
                            if (families.length > 1) {
                                family = Families.findOne({'createdUser._id': user._id, isDefault: true}, {fields: {belongTo: 0, createdUser: 0 }});
                                if (!family) {
                                    family = families[0];
                                }
                            } else {
                                family = families[0];
                            }
                            let gateway = {};
                            if(family){
                                gateway = Gateways.findOne({'familyId': family._id, isDefault: true});
                                /*if (gateways.length > 1) {
                                    gateway = Gateways.findOne({familyId: family._id, isDefault: true});
                                    if (!gateway) {
                                        gateway = gateways[0];
                                    }
                                } else {
                                    gateway = gateways[0];
                                }*/
                            }
                            user['family_id'] = family && family._id ? family._id : '';
                            user['family_name'] = family && family.name ? family.name : '';
                            user['gateway_id'] = gateway && gateway.devId ? gateway.devId : '';
                            user['gateway_name'] = gateway && gateway.name ? gateway.name : '';
                            return {success: true, resultCode: 1000, result: {user: user,/* family: family, gateway: gateway,*/ error: ''}}
                        }else{
                            return {success: false, result: {error: '未获取到登录用户信息'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有获取到信息'}, resultCode: 1002};
                }
            }
        });
        /*//获取用户信息
        Api.addRoute('getUser', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var logintoken = param.token; 
                        const userId = param.userId;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken},{fields: {username: 1, nickname: 1}});
                        if(user) {
                            const u = Meteor.users.findOne({_id: userId});
                            return {success: true, resultCode: 1000, result: {user: u, error: ''}}
                        }else{
                            return {success: false, result: {error: '未获取到用户信息'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有获取到信息'}, resultCode: 1002};
                }
            }
        });*/
        //用户退出
        Api.addRoute('userOutLogin', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            const u = Meteor.users.update({_id: user._id},{ $pull: { "services.resume.loginTokens": { token: logintoken } } });
                            if(u){
                                return {success: true, result: '退出成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '退出登录失败！', resultCode: 1004};
                            }

                        }else{
                            return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '请求出现问题！', resultCode: 1002};
                }
            }
        });
        //密码重置
        Api.addRoute('updatePassword', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const oldPassword = param.oldPwd;
                        const newPassword = param.newPwd;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":logintoken});
                        if(user) {
                            var result = Accounts._checkPassword(user, oldPassword);
                            if(!result.error){
                                const res = Accounts.setPassword(user._id, newPassword);
                                return {success: true, result: '用户密码修改成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '旧密码不正确，请确认！', resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '请求出现问题！', resultCode: 1002};
                }
            }
        });
       /* // 添加新用户
        Api.addRoute('addUser', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const token = param.token;
                        const deviceId = param.deviceId;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        if(user) {
                            delete param.token;
                            delete param.deviceId;
                            param['relationshipId'] = user._id;
                            param['userType'] = 'shipUser';
                            param['fingerprints'] = [];
                            if(deviceId && deviceId != ''){
                                param['devices'] = [deviceId];
                            }else{
                                param['devices'] = [];
                            }
                            const u = Meteor.users.insert(param);
                            if(u){
                                return {success: true, result: '用户添加成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '用户添加失败！', resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });*/
        /*//添加锁与用户的关联关系
        Api.addRoute('addUserDevice', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const token = param.token;
                        const deviceId = param.deviceId;
                        const userId = param.userId;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        if(user) {
                            const u = Meteor.users.update({_id: userId}, {$addToSet : {devices : deviceId}});
                            if(u){
                                return {success: true, result: '锁添加用户成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '锁添加用户失败！', resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });*/
       /* // 获取锁的用户
        Api.addRoute('getUserListByDeviceId', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const token = param.token;
                        const deviceId = param.deviceId;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        console.log('sssss : ', user);
                        // if(user) {
                            const users = Meteor.users.find({devices: deviceId, userType: 'shipUser'}).fetch();
                            if(users){
                                return {success: true, result: users, resultCode: 1000};
                            }else{
                                return {success: false, result: [], resultCode: 1002};
                            }
                        // }else{
                        //     return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        // }
                    }
                    // return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });*/
        // 获取管理员的用户
       /* Api.addRoute('getUserList', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const token = param.token;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        // if(user) {
                            const users = Meteor.users.find({relationshipId: user._id, userType: 'shipUser'}).fetch();
                            if(users){
                                return {success: true, result: users, resultCode: 1000};
                            }else{
                                return {success: false, result: [], resultCode: 1002};
                            }
                        // }else{
                        //     return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        // }
                    }
                    // return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });*/
        // 删除用户
        Api.addRoute('deleteUser', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const token = param.token;
                        const userId = param.userId;
                        var user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        if(user) {
                            const users = Meteor.users.remove(userId);
                            if(users){
                                return {success: true, result: '用户删除成功！', resultCode: 1000};
                            }else{
                                return {success: false, result: '用户删除失败！', resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: '未获取到登录用户的信息！', resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        // 测试服务运行是否正常
        Api.addRoute('checkService', {authRequired: false}, {
            post: {
                action() {
                    return {success: true, msg: 'ours-locks接口服务运行正常！'};
                }
            }
        });
        //微信公共号登录
        // 通过接口登录
        Api.addRoute('userWXLogin', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        var param = this.bodyParams;
                        var username = param.username;
                        var password = param.password;
                        var openId = param.openId;
                        var user = Meteor.users.findOne({username: username});
                        if(user){
                            var result = Accounts._checkPassword(user, password);
                            if(!result.error){
                                Accounts._insertHashedLoginToken( result.userId, { token: openId} );
                                const families = Families.find({'createdUser._id': user._id}, {fields: {belongTo: 0, createdUser: 0 }}).count();
                                let bl = false;
                                if(families > 0){
                                    bl = true;
                                }
                                return {success: true, result: {token: openId, families: bl, error: ''}, resultCode: 1000};
                            }else{
                                return {success: false, result: {error: '密码不正确，登录失败！'}, resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: {error: '手机号未注册！'}, resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写登录信息！', resultCode: 1002};
                }
            }
        });
        //添加家属
        Api.addRoute('addJiaShu', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const username = param.username;
                        const relationshipType = param.relationshipType;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token":token});
                        if(user){
                            const userId = Meteor.users.insert({relationshipId: user._id, username: username, relationshipType: relationshipType, userType: 'shipUser'});
                            if(userId){
                                return {success: true, result: {error: '亲属添加成功！'}, resultCode: 1000};
                            }else{
                                return {success: false, result: {error: '亲属添加失败！'}, resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: {error: '手机号未注册！'}, resultCode: 1002};
                        }
                    }
                    return {success: false, result: '没有填写登录信息！', resultCode: 1002};
                }
            }
        });
        //根据openId判断用户是否存在
        Api.addRoute('isExistByOpenId', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const openId = param.openId;
                        if(openId && openId != ''){
                            const user = Meteor.users.findOne({"openId":openId});
                            if(user){
                                if(user.username && (/^1[3|4|5|8][0-9]\d{4,8}$/.test(user.username))){
                                    const u = Meteor.users.findOne({"services.resume.loginTokens.token":openId});
                                    if(!u){
                                        Accounts._insertHashedLoginToken( user._id, { token: openId} );
                                    }
                                    return {success: true, result: {user: u}, resultCode: 1002};
                                }else{
                                    return {success: false, result: {error: '需要关联手机号！'}, resultCode: 1002};
                                }

                            }else{
                                return {success: false, result: {error: '微信用户未注册！'}, resultCode: 1002};
                            }
                        }else{
                            return {success: false, result: {error: '微信登录出错！'}, resultCode: 1002};
                        }

                    }
                    return {success: false, result: '没有填写登录信息！', resultCode: 1002};
                }
            }
        });
        //根据openId及手机号处理用户信息 
        Api.addRoute('checkUserByPhone', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const openId = param.openId;
                        const telephone = param.telephone;
                        if(openId && openId != ''){
                            const user = Meteor.users.findOne({username: telephone});
                            if(user){
                                const rid = Meteor.users.update({_id: user._id}, {$set: {openId: openId}});
                                Accounts._insertHashedLoginToken( user._id, { token: openId} );
                                if(rid){
                                    return {success: true, result: {error: '微信连接成功！', msg: '用户已在app上注册'}, resultCode: 1000};
                                }else{
                                    return {success: false, result: {error: '微信连接失败！'}, resultCode: 1002};
                                }
                            }else{
                                const _id = Meteor.users.insert({username: telephone, nickname: telephone, openId: openId});
                                if(_id){
                                    Accounts.setPassword(_id, '123456');
                                    Accounts._insertHashedLoginToken( _id, { token: openId} );
                                    return {success: true, result: {error: '微信连接成功！', msg : '用户还没在app上注册'}, resultCode: 1000};
                                }else{
                                    return {success: false, result: {error: '微信连接失败！'}, resultCode: 1002};
                                }
                            }
                        }else{
                            return {success: false, result: {error: '微信登录出错！'}, resultCode: 1002};
                        }
                        
                    }
                    return {success: false, result: '没有填写登录信息！', resultCode: 1002};
                }
            }
        });
    });
}